package com.cskaoyan.service;


import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.common.Constant;
import com.cskaoyan.bean.marketBean.MarketStorage;
import com.cskaoyan.bean.marketBean.MarketStorageExample;

import com.cskaoyan.mapper.marketMapper.MarketStorageMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 曾添乐啦
 * @since 2022/12/28 20:42
 */
@Service
public class AdminStorageServiceImpl implements AdminStorageService {

    @Autowired
    MarketStorageMapper marketStorageMapper;


    /**
     * 请求参数
     * page: 1
     * limit: 20
     * sort: add_time
     * order: desc
     *
     * @param info
     * @param key
     * @param name
     * @return
     */
    //TODO：对象存储info首页
    @Override
    public CommonData queryStorageList(BasePageInfo info, String key, String name) {


        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        //开启分页
        PageHelper.startPage(info.getPage(), info.getLimit());

        //执行查询过程中拼接分页信息
        // 如果按照page=5 limit = 10做分页，goods.size()会是多少 10
        //使用逆向工程提供的marketStorageMapper.selectByExample()方法，根据形参知需要new一个实例对象
        MarketStorageExample example = new MarketStorageExample();
        //排序
        example.setOrderByClause(info.getSort() + " " + info.getOrder());
        //example.createCriteria();该方法用来拼接查询条件,
        MarketStorageExample.Criteria criteria = example.createCriteria();
        if (key != null && !"".equals(key)) {
            criteria.andKeyLike("%" + key + "%");
        }
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        List<MarketStorage> marketStorages = marketStorageMapper.selectByExample(example);

        // 将查询结果作为有参构造方法的形参传入，可以获得PageInfo
        PageInfo<MarketStorage> pageInfo = new PageInfo<>(marketStorages);

        // list()方法不做分页的情况下可以查到的数据总量

        return CommonData.data(pageInfo);
    }

    /**
     * `id`
     * `key` varchar(63) 文件的唯一索引',
     * `name` varchar(255) '文件名',
     * `type` varchar(20)  '文件类型',
     * `size` int  '文件大小',
     * `url` varchar(255)  '文件访问链接',
     * `add_time` datetime  '创建时间',
     * `update_time` datetime  '更新时间',
     * `deleted` tinyint(1)  '逻辑删除',
     * 添加文件需要注意
     *
     * @param file
     * @return
     */
    //todo：新增
    @Override
    public MarketStorage addStorage(MultipartFile file) {
     /*   //获取 文件名
        String filename = file.getOriginalFilename();

        //获取 文件类型
        String type = file.getContentType();

        //获取 文件大小
        int size = (int) file.getSize();

        //获取 文件的唯一索引
        //设置一个UUID
        UUID uuid = UUID.randomUUID();
        //将UUID和图片文件后缀做拼接生成唯一key,文件的唯一索引
        //获取图片后缀
        int index = type.indexOf("/");
        String key = uuid.toString() + "." + type.substring(index + 1);

        //文件实际存放位置
        // 比如我们要保存到D:\tmp路径下，保存的文件名叫banner.png ，我们就要提供一个这样的File
        //File file = new File("D:\\tmp\\banner.png");
        //File file = new File("D:\\tmp\\","banner.png");
        // 保存时以原始的文件名保存，如果上传同名文件会覆盖 → JavaEE  hashcode和uuid
        File filetrue = new File("D:\\tmp\\", filename);
        try {
            file.transferTo(filetrue);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //把上传文件数据存放到数据库
        MarketStorage marketStorage = new MarketStorage();

        marketStorage.setKey(key);
        marketStorage.setName(filename);
        marketStorage.setType(type);
        marketStorage.setSize(size);
        //TODO：如何获取文件访问链接,暂且设置为空
        marketStorage.setUrl("D:\\tmp\\"+filename);
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setDeleted(false);
        marketStorageMapper.insert(marketStorage);


        return marketStorage;*/
        //获取 文件名
        String filename = file.getOriginalFilename();
        String suuid = UUID.randomUUID().toString();
        filename = suuid + "-" + filename;

        //获取 文件类型
        String type = file.getContentType();

        //获取 文件大小
        int size = (int) file.getSize();

        //获取 文件的唯一索引
        //设置一个UUID
        UUID uuid = UUID.randomUUID();
        //将UUID和图片文件后缀做拼接生成唯一key,文件的唯一索引
        //获取图片后缀
        int index = type.indexOf("/");
        String key = uuid.toString() + "." + type.substring(index + 1);

        //文件实际存放位置
        // 比如我们要保存到D:\tmp路径下，保存的文件名叫banner.png ，我们就要提供一个这样的File
        //设置多级目录，解决所有文件全部都在一个目录内的问题
        int hashCode = filename.hashCode();
        String hexString = Integer.toHexString(hashCode);
        char[] chars = hexString.toCharArray();
        String basePath = "";
        for (char aChar : chars) {
            basePath = basePath + "/" + aChar;
        }
        basePath += "/";

        String path = Constant.BASE_MAPPING_LOCATION + basePath + filename;
        File filetrue = new File(path);
        if(!filetrue.getParentFile().exists()){
            filetrue.getParentFile().mkdirs();
        }
        try {
            file.transferTo(filetrue);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //把上传文件数据存放到数据库
        MarketStorage marketStorage = new MarketStorage();

        marketStorage.setKey(key);
        marketStorage.setName(filename);
        marketStorage.setType(type);
        marketStorage.setSize(size);
        //TODO：如何获取文件访问链接,暂且设置为空
        marketStorage.setUrl(Constant.BASE_URL + basePath + filename);
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setDeleted(false);
        marketStorageMapper.insertSelective(marketStorage);


        return marketStorage;
    }

    //todo:删除
    @Override
    public int delete(MarketStorage marketStorage) {
        int deleteAffacted = marketStorageMapper.deleteByPrimaryKey(marketStorage.getId());
        return deleteAffacted;
    }

    //修改
    @Override
    public int update(MarketStorage marketStorage) {
        int updateAffected = marketStorageMapper.updateByPrimaryKey(marketStorage);
        return updateAffected;
    }
}
